import axios, { AxiosRequestConfig, AxiosResponse, InternalAxiosRequestConfig } from 'axios';
import { Modal } from 'antd';
import React from 'react';
import LoginForm from '../app/Login/LoginFrom';
import { logout } from './localStorageManager';

// 创建 Axios 实例
const axiosInstance = axios.create({
  baseURL: process.env.NEXT_PUBLIC_BASE_URL, // 替换为你的 API 地址
  timeout: 1200000,
});

let needToken = true;

// 请求拦截器
axiosInstance.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    if (needToken) {
      const token = localStorage.getItem('token'); // 假设 token 存储在 localStorage
      if (token) {
        config.headers['X-Access-Token'] = `${token}`;
      } else {
        // 未登录，弹出登录框
        // showModal();
        // return Promise.reject('未登录');
        logout();
      }
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

// 弹出登录框
const showModal = () => {
  Modal.info({
    title: '请登录',
    content: (
      <div>
        <LoginForm 
          open={false} 
          setOpen={(open: boolean): void => {
            throw new Error('Function not implemented.');
          }}
          firmName=""
        />
      </div>
    ),
    onOk() { },
  });
};

// 封装 GET 请求
export const get = <T = any>(url: string, params: Record<string, any> = {}, isNeedToken: boolean = true): Promise<T> => {
  needToken = isNeedToken;
  return axiosInstance.get(url, {
    params,
  })
    .then((response: AxiosResponse<T>) => response.data)
    .catch(error => {
      console.error('GET 请求错误:', error);
      if (error.response && error.response.status === 401) {
        logout();
      }
      throw error;
    });
};

export const putAxios = <T = any>(url: string, data: Record<string, any> = {}, isNeedToken: boolean = true): Promise<T> => {
  needToken = isNeedToken;
  return axiosInstance.put(url, data)
    .then((response: AxiosResponse<T>) => response.data)
    .catch(error => {
      console.error('PUT 请求错误:', error);
      throw error;
    });
}

export const deleteAxios = <T = any>(url: string, params: Record<string, any> = {}, isNeedToken: boolean = true): Promise<T> => {
  needToken = isNeedToken;
  return axiosInstance.delete(url, {
    params,
  })
    .then((response: AxiosResponse<T>) => response.data)
    .catch(error => {
      console.error('DELETE 请求错误:', error);
      throw error;
    });
}

// 封装 POST 请求
export const post = <T = any>(url: string, data: Record<string, any> = {}, isNeedToken: boolean = true): Promise<T> => {
  needToken = isNeedToken;
  return axiosInstance.post(url, data)
    .then((response: AxiosResponse<T>) => response.data)
    .catch(error => {
      console.error('POST 请求错误:', error);
      if (error.response && error.response.status === 401) {
        logout();
      }
      throw error;
    });
};

// 新增函数：检查是否已登录
export const isLoggedIn = (): boolean => {
  if (typeof window !== 'undefined') {
    const token = localStorage.getItem('token');
    return !!token; // 如果 token 存在，返回 true，否则返回 false
  }
  return false; // 在服务器端渲染时返回 false
};

export default axiosInstance;
